package cn.kgc.common.security.service;

import cn.kgc.common.constant.RedisPrefix;
import cn.kgc.common.constant.ResultConstant;
import cn.kgc.common.constant.SystemConstant;
import cn.kgc.common.util.HttpException;
import cn.kgc.common.util.RedisUtil;
import cn.kgc.api.entity.CustomerUser;
import cn.kgc.api.entity.Users;
import cn.kgc.api.service.UsersService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;

/**
 * @Author: kgc
 * @Date: 2024-04-09
 * @Description: SpringSecurity认证业务类
 * @Version: v1.0
 */
@Service("userDetailService")
public class UserDetailServiceImpl implements UserDetailsService {
    @Resource
    private UsersService usersService;

    @Resource
    private RedisUtil redisUtil;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名获得用户信息
        LambdaQueryWrapper<Users> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Users::getUserName,username);
        Users sysUser = usersService.getOne(queryWrapper);
        if(sysUser==null){
            throw new HttpException(ResultConstant.LOGIN_USERNAME_PASSWORD_ERROR);
        }
        //用户离职
        if(sysUser.getState().equals(SystemConstant.SysUserStatus.TURNOVER.getCode())){
            throw new HttpException(ResultConstant.LOGIN_DIMISSION_ERROR);
        }
        redisUtil.set(RedisPrefix.SYSTEM_USER_PERMS + sysUser.getUserId(), Collections.emptyList());
        //返回用户信息
        return new CustomerUser(sysUser,Collections.emptyList());
    }
}
